import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService } from '@delon/theme';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { ServiceResult, Constant } from '@core/constant';
import { ProductSkuEditV2Component } from '@shared/component/product-sku-edit-v2/product-sku-edit-v2.component';

@Component({
  selector: 'product-add',
  templateUrl: './product-add.component.html',
  styleUrls: ['./product-add.component.less']
})
export class ProductAddComponent implements OnInit, OnDestroy {

  product: {[propName: string]: any;} = {}
  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;

  saleing = false;
  years = [];
  brands = [];
  brandLines = [];
  categorys = [];
  userGroups = [];
  seasons = [];
  seriess = [];
  proTypes = [];
  frameTypes = [];
  isAds = [{ text: '广告款', value: this.cnt.BoolUtil.TRUE}, { text: '普通款', value: this.cnt.BoolUtil.FALSE }];
  isCms = [{ text: '是', value: this.cnt.BoolUtil.TRUE}, { text: '否', value: this.cnt.BoolUtil.FALSE }];
  @ViewChild("skuEdit2") skuEdit2: ProductSkuEditV2Component;
  private sub: any;


  avatarUrl: string;
  loading = false;
  uploadUrl = '';
  avatarParam = { type: 'Avatar', userId: ''};


  constructor(
    private msg: NzMessageService,
    private modalService: NzModalService,
    private productService: ProductService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private router: Router,
    private cnt: Constant,
    private comm: CommService
  ) {}

  ngOnInit(): void {
    this.loadBrandLines();
    this.loadCategorys();
    this.loadSeasons();
    this.loadBrands();
    this.loadUserGroup();
    this.loadYears();

    setTimeout(() => {
        this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 100);
    this.titleService.setTitle("添加订单");
  }

  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  loadYears() {
    this.years = [];
    this.comm.getYear().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.years.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }

  // 加载产品季节
  loadSeasons() {
    this.seasons = [];
    this.comm.getSeasons().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.seasons.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }

  // 加载品牌分类
  loadCategorys() {
    this.categorys = [];
    this.comm.getCategory().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.categorys.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }

  // 加载品项列表
  loadBrandLines() {
    this.brandLines = [];
    this.comm.getBrandLine().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.brandLines.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }

  // 加载品牌列表
  loadBrands() {
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.brands.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }

  loadUserGroup() {
    this.userGroups = [];
    this.comm.getUserGroup().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.userGroups.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }



  reset(i) {
    // 基本信息重置
    if (i == 0) {
      this.product.brandLine = null;
      this.product.category = null;
      this.product.season = null;
      this.product.brand = null;
      this.product.year = null;
      this.product.userGroup = null;
      this.product.isAd = null;
      this.product.isCm = null;
    } else if (i == 1) {
      this.skuEdit2.dataTable = [[], [], [], [], []];
      this.skuEdit2.batch = [];
    }
  }

  save() {

    if (!this.product.brandLine) {
      this.msg.warning("请选择品项");
      return;
    }

    if (!this.product.category) {
      this.msg.warning("请选择分类");
      return;
    }

    if (!this.product.brand) {
        this.msg.warning("请选择品牌");
        return;
    }

    if (!this.product.season) {
      this.msg.warning("请选择产品季");
      return;
    }

    if (!this.product.year) {
        this.msg.warning("请选择年份");
        return;
    }

    if (!this.product.userGroup) {
        this.msg.warning("请选择款式");
        return;
    }

    let data = this.skuEdit2.dataTable;
    if (data.length == 0) {
      this.msg.warning("请填写商品信息");
      return;
    }

    let prods = [];
    // 组织数据
    for (let prod of data) {
        if (prod[1]) {
            if (!prod[2]) {
                this.msg.warning('色号不能空');
                return;
            }
            let dto = {
                brandLine: this.product.brandLine,
                category: this.product.category,
                season: this.product.season,
                brand: this.product.brand,
                userGroup: this.product.userGroup,
                year: this.product.year,
                isAd: this.product.isAd ? this.product.isAd : this.cnt.BoolUtil.FALSE,
                isCm: this.product.isCm ? this.product.isCm : this.cnt.BoolUtil.FALSE,
                status: this.saleing ? this.cnt.BoolUtil.TRUE : this.cnt.BoolUtil.FALSE,
                style: prod[1],
                colorCd: prod[2],
                productCd: prod[3],
                sap: prod[4],
                img: prod[0] ? prod[0]['id'] : '',
                tradeDPrice: prod[5],
                retailDPrice: prod[6],
                marketDPrice: prod[7],
                pfTexture: prod[8],
                lensTexture: prod[10],
                templeTexture: prod[12],
                colorSpec: prod[9],
                lensSpec: prod[11],
                templeSpec: prod[13],
                spec: prod[14],
            }
            prods.push(dto);
        }

    }
    if (prods.length == 0) {
      this.msg.warning("请填写产品信息");
      return;
    }

    // 调用接口
    this.loading = true;
    this.productService.addPro(prods).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.loading = false;
      if (data.status === 200) {
        if (data.data.length != 0 && prods.length != data.data.length) {
          this.msg.warning(`成功添加${prods.length - data.data.length}条记录, ${data.data.length}条插入失败`);
          this.emit.sendMessage("RELOAD_GOODS_LIST");
        } else if (data.data.length != 0 && prods.length == data.data.length) {
          this.msg.error(`添加失败:${data.data.toString()}`);
        } else if (data.data.length === 0) {
          this.msg.success("添加成功");
          this.emit.sendMessage("RELOAD_GOODS_LIST");
          this.reset(0);
          this.reset(1);
        }
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  back() {
    this.router.navigate(['/prod/product']);
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`No support: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.warning('The pic file not more than 2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

}
